class InformationClerkController < ApplicationController
  include Authorizable
  include MerchantHelper

  before_action :is_information_clerk

  def create
    data = gather_information_clerk_data
    data[:password] = "123456"
    data[:password_confirmation] = "123456"

    if User.create(data)
      redirect_to "/"
    else
      flash[:danger] = "创建失败"
      redirect_to :back
    end
  end

  def show
    @today_count = get_user_count_by(@user.id, beginning_of_today)
    @week_count = get_user_count_by(@user.id, beginning_of_week)
    @month_count = get_user_count_by(@user.id, beginning_of_month)
    @year_count = get_user_count_by(@user.id, beginning_of_year)
    @total_count = Merchant.where(information_clerk_id: @user.id).count
    @merchants = Merchant.select(:id, :name, :location, :created_at).where(information_clerk_id: @user.id).page(params[:page])
  end

  def update
    if @user.update(gather_information_clerk_data)
      flash[:danger] = "更新成功"
      redirect_to "/"
    else
      flash[:danger] = "更新失败"
      redirect_to :back
    end
  end

  private
    def gather_information_clerk_data
      {
        name: params[:name],
        mobile: params[:mobile],
        user_type: USER_TYPE["信息录入员"],
        is_active: params[:is_active].nil? ? false : true
      }
    end

    def is_information_clerk
      if params[:id] && @user = User.find_by(id: params[:id])
      else
        flash[:danger] = "不是信息录入员"
        redirect_to :back
      end
    end
end